package interview.juc.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 * @Author: zhangrongqing
 * @Date: 2019/12/9 15:07
 */
public class ProducerAndConsumerCondition {
    private Lock lock;
    private Condition condition;

    public ProducerAndConsumerCondition(Lock lock) {
        this.lock = lock;
        this.condition = lock.newCondition();
    }

    public class Consumer extends Thread {

        @Override
        public void run() {
            try {
                lock.lock();                          //1.获取锁
                System.out.println(Thread.currentThread().getName() + "获取到线程");
                condition.await();                   //2.释放锁，沉睡，等待被唤醒    7.被唤醒，继续工作
                System.out.println(Thread.currentThread().getName() + ":我被唤醒了！");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();                       //真正释放锁
            }
        }
    }

    public class Producer extends Thread {

        @Override
        public void run() {
            try {
                lock.lock();                    //3.释放锁
                System.out.println(Thread.currentThread().getName() + "我获取了线程");
                condition.signalAll();          //4.唤醒锁
                System.out.println(Thread.currentThread().getName() + "释放了线程");
                Thread.sleep(10000);     //5.想看看signAll是不是释放了？不会只有等待unlock以后才会
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();                  //6.释放锁
            }
        }
    }
}
